<template>
  <div class="chat">
    <van-nav-bar :fixed="true" :title="userInfo.userName" left-arrow @click-left="onClickLeft">
      <template #left>
        <van-icon name="arrow-left" color="#000000" size="22" />
      </template>
      <template #right>
        <van-icon name="ellipsis" color="#000000" size="22" />
      </template>
    </van-nav-bar>
    <div class="content" ref="chatMain" :style="{height:(fullHeight-46-46) +'px' }">
      <div v-for="(item,index) in getChatList" :key="index">
        <div class="message-box" v-if="item.fromUserId == user.userId">
          <van-row>
            <van-col span="20">
              <div class="text-box-right">
                <span>{{item.msg}}</span>
              </div>
            </van-col>
            <van-col span="4">
              <div class="img-box">
                <van-image
                  width="40px"
                  height="40px"
                  fit="fill"
                  radius="5"
                  :src="item.fromUserImg"
                />
              </div>
            </van-col>
          </van-row>
        </div>

        <div class="message-box" v-else>
          <van-row>
            <van-col span="4">
              <div class="img-box">
                <van-image
                  width="40px"
                  height="40px"
                  fit="fill"
                  radius="5"
                  :src="item.fromUserImg"
                />
              </div>
            </van-col>
            <van-col span="20">
              <div class="text-box-left">
                <span>{{item.msg}}</span>
              </div>
            </van-col>
          </van-row>
        </div>
      </div>
    </div>

    <div class="opt-box">
      <van-row>
        <van-col span="3">
          <div class="text-voice">
            <van-icon name="volume-o" size="18" @click="voice" />
          </div>
        </van-col>
        <van-col span="15">
          <van-field
            class="text-input"
            v-model="message"
            rows="1"
            :autosize="autosize"
            type="textarea"
            maxlength="50"
            input-align="left"
          />
        </van-col>
        <van-col span="6">
          <div class="opt-btn">
            <van-row>
              <van-col span="12" class="opt-smile">
                <van-icon name="smile-o" size="25" @click="smile" />
              </van-col>
              <van-col span="12" class="opt-smile-add" v-if="message.length == 0">
                <van-icon name="add-o" size="23" @click="addOther" />
              </van-col>
              <van-col span="12" class="opt-smile-send" v-if="message.length > 0">
                <van-tag type="success" size="medium" @click="send">发送</van-tag>
              </van-col>
            </van-row>
          </div>
        </van-col>
      </van-row>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";

export default {
  name: "User",
  data() {
    return {
      friendId: "",
      userInfo: "",
      fullWidth: document.documentElement.clientWidth,
      fullHeight: document.documentElement.clientHeight,
      message: "",
      autosize: { maxHeight: 100, minHeight: 22 },
      list: []
    };
  },
  methods: {
    ...mapMutations(["updateIsChatting"]),
    ...mapActions(["asyncSaveChatList"]),
    onClickLeft() {
      this.$router.push("/index");
    },
    //获取用户信息
    getUserInfo() {
      this.axios
        .get(this.server.BaseUrl + "/user/" + this.friendId)
        .then(res => {
          if (res.data.status) {
            this.userInfo = res.data.data;
          } else {
            this.$toast(res.data.message);
          }
        })
        .catch(err => {
          this.$toast("网络异常");
          console.log(err);
        });
    },
    /**
     * 动态获取浏览器宽高
     */
    handleResize() {
      this.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = document.documentElement.clientHeight;
    },
    //发送消息
    send() {
      console.log(this.message);
      if (this.message.length > 0) {
        //1.初始化消息数据
        let msgData = {
          fromUserId: this.user.userId,
          fromUserName: this.user.userName,
          fromUserImg: this.user.userImg,
          toUserId: this.userInfo.userId,
          toUserName: this.userInfo.userName,
          toUserImg: this.userInfo.userImg,
          msg: this.message,
          time: new Date().getTime(),
          read: false
        };

        this.axios
          .post(this.server.BaseUrl + "/sendToUser", msgData)
          .then(res => {
            if (res.data.status) {
              this.handleMessage(msgData);
              this.message = "";
            } else {
              this.$toast("消息发送失败");
            }
          })
          .catch(err => {
            console.log(err);
            this.$toast("服务维护中...");
          });
      }
    },
    //语音消息
    voice() {
      this.$toast("功能未开放！");
    },
    //选择表情
    smile() {
      this.$toast("功能未开放！");
    },
    //附件功能
    addOther() {
      this.$toast("功能未开放！");
    },
    //处理消息
    handleMessage(msgData) {
      let list = this.chatList;
      //判断列表是否为空
      if (list.length > 0) {
        let exist = false;
        list.forEach(element => {
          //已有聊天信息，更新数据
          if (element.friendId == msgData.toUserId) {
            exist = true;
            if (this.isChatting) {
              msgData.read = true;
              element.count = 0;
            } else {
              element.count++;
            }
            element.lastMsg = msgData.msg;
            element.lastMsgTime = msgData.time;
            element.msgList.push(msgData);
          }
        });

        //没有聊天数据，增加新的聊天数据
        if (!exist) {
          let msgList = [];
          if (this.isChatting) {
            msgData.read = true;
          }
          msgList.push(msgData);
          let chatData = {
            count: 1,
            lastMsg: msgData.msg,
            lastMsgTime: msgData.time,
            friendId: msgData.toUserId,
            friendUserName: msgData.toUserName,
            friendUserImg: msgData.toUserImg,
            msgList: msgList
          };
          if (this.isChatting) {
            chatData.count = 0;
          }
          list.push(chatData);
        }
      } else {
        //初始化列表数据
        let msgList = [];
        if (this.isChatting) {
          msgData.read = true;
        }
        msgList.push(msgData);
        let chatData = {
          count: 1,
          lastMsg: msgData.msg,
          lastMsgTime: msgData.time,
          friendId: msgData.toUserId,
          friendUserName: msgData.toUserName,
          friendUserImg: msgData.toUserImg,
          msgList: msgList
        };
        if (this.isChatting) {
          chatData.count = 0;
        }
        list.push(chatData);
      }
      this.asyncSaveChatList(list);
    }
  },
  computed: {
    ...mapState(["user", "chatList", "isChatting", "wsIsLive"]),
    getChatList: function() {
      let msgList = [];
      let list = this.chatList;
      list.forEach(item => {
        if (item.friendId == this.friendId) {
          msgList = item.msgList;
        }
      });
      return msgList;
    }
  },
  mounted() {
    this.$refs.chatMain.scrollTop = this.$refs.chatMain.scrollHeight;
    // 监听window的resize事件
    window.onresize = () => {
      this.$refs.chatMain.scrollTop = this.$refs.chatMain.scrollHeight;
    };
  },
  created() {
    window.addEventListener("resize", this.handleResize);
    this.friendId = this.$route.query.userId;
    //获取用户信息
    this.getUserInfo();
    //激活正在聊天界面状态
    this.updateIsChatting(true);
  },
  beforeDestroy: function() {
    window.removeEventListener("resize", this.handleResize);
  },
  destroyed() {
    this.updateIsChatting(false);
  },
  watch: {
    getChatList() {
      this.$nextTick(function() {
        this.$refs.chatMain.scrollTop = this.$refs.chatMain.scrollHeight;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.chat {
  width: 100%;
  height: 100%;

  .van-nav-bar {
    background-color: #ffffff;
  }

  .content {
    width: 100%;
    overflow-y: scroll;
    margin-top: 46px;
    background-color: #eae8e8;

    .clearfix::before,
    .clearfix::after {
      content: "";
      display: table;
      clear: both;
    }

    .message-box {
      margin-top: 15px;
      margin-bottom: 15px;

      .img-box {
        height: 40px;
        width: 40px;
        border-radius: 5px;
        margin: auto;
      }

      .text-box-left,
      .text-box-right {
        min-height: 18px;
        background-color: white;
        padding: 10px 5px;
        border-radius: 5px;
        max-width: 200px;
        display: inline-block;
        font-size: 13px;
      }

      .text-box-right {
        float: right;
        background-color: #65c593;
        color: white;
      }
    }
  }

  .opt-box {
    min-height: 46px;
    width: 100%;
    position: fixed;
    bottom: 0px;
    background-color: #f1f1f3;

    .van-col {
      height: 46px;
      line-height: 46px;

      .text-voice {
        height: 46px;
        line-height: 46px;
        text-align: center;
        padding-top: 5px;
        position: fixed;
        left: 3%;
        bottom: -4px;
      }

      .text-input {
        min-height: 35px;
        margin-top: 5px;
        border-radius: 5px;
        position: fixed;
        bottom: 5px;
        left: 11%;
        width: 66%;
      }

      .opt-btn {
        position: fixed;
        bottom: 0px;
        right: 10%;

        .opt-smile {
          padding-top: 8px;
          position: fixed;
          bottom: 0px;
          left: 79%;
        }

        .opt-smile-add {
          padding-top: 8px;
          position: fixed;
          bottom: 0px;
          left: 89%;
        }

        .opt-smile-send {
          padding-top: 8px;
          position: fixed;
          bottom: 8px;
          left: 87%;
        }
      }

      .van-cell {
        padding: 6px 5px;
      }
    }
  }
}
</style>